package com.wd.live.ui.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.jcodecraeer.xrecyclerview.XRecyclerView.LoadingListener
import com.wd.live.R
import com.wd.live.databinding.ActivityOpenLiveBinding
import com.wd.live.databinding.FragmentPlazaBinding
import com.wd.live.databinding.ItemSuqareListBinding
import com.wd.live.tool.BindingViewHolder
import com.wd.live.tool.LocalData
import com.wd.live.tool.lunchActivity
import com.wd.live.tool.newBindingViewHolder
import com.wd.live.ui.activity.LookLiveActivity
import com.wd.live.viewmodel.PlazaViewModel

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * 广场
 */
class PlazaFragment : Fragment(R.layout.fragment_plaza) {

    private var currentTabId: Int? = 0
    private var tabList: ArrayList<LocalData.TypeInfo> = ArrayList()
    private val viewModel: PlazaViewModel by viewModels(ownerProducer = { this })
    private var _binding: FragmentPlazaBinding? = null
    private val binding get() = _binding!!
    private var mAdapter: MyAdapter? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentPlazaBinding.inflate(inflater, container, false)
        return binding.root
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewModel.getTypeList()

        viewModel.typeInfo.observe(viewLifecycleOwner) {
            initTabView(it)
        }
        viewModel.liveList.observe(viewLifecycleOwner) {
            binding.list.refreshComplete()
            binding.list.loadMoreComplete()
            mAdapter?.setData(it)
        }
        binding.list.apply {
            mAdapter = MyAdapter(ArrayList()) {
                //看播
                lunchActivity<LookLiveActivity>("live_data", it)
            }.apply {
                notifyDataSetChanged()
            }
            layoutManager = GridLayoutManager(context, 2)
            adapter = mAdapter

            setLoadingListener(object : LoadingListener{
                override fun onRefresh() {
                    currentTabId?.let {
                        refreshAndMore(it,true)
                    }
                }

                override fun onLoadMore() {
                    currentTabId?.let {
                        refreshAndMore(it,false)
                    }
                }
            })
        }
    }

    private fun refreshAndMore(it: Int, isRefresh: Boolean) {
        mAdapter?.isRefresh = isRefresh
        viewModel.getFindLiveList(it, isRefresh)
    }

    /**
     * 初始化tabView
     */
    private fun initTabView(it: ArrayList<LocalData.TypeInfo>) {
        tabList = it
        it.forEach {_tab ->
            binding.tabView.addTab(binding.tabView.newTab().setText(_tab.name))
        }
        binding.tabView.addOnTabSelectedListener(object : OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                currentTabId = tabList[tab!!.position].id
                currentTabId?.let {
                    viewModel.getFindLiveList(it, true)
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }
        })
        binding.tabView.getTabAt(1)?.select()
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @return A new instance of fragment PlazaFragment.
         */
        @JvmStatic
        fun newInstance() = PlazaFragment()
    }

    class MyAdapter(
        private var list: ArrayList<LocalData.LiveShow>,
        private val function: (LocalData.LiveShow) -> Unit
    ) : Adapter<BindingViewHolder<ItemSuqareListBinding>>() {
        var isRefresh: Boolean = true

        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): BindingViewHolder<ItemSuqareListBinding> {
            //通过这个方法创建一个viewHolder。这个viewHolder是基于viewBinding的
            return newBindingViewHolder(parent)
        }
        fun setData(data: ArrayList<LocalData.LiveShow>) {
            if(isRefresh) {
                this.list = data
            } else {
                list.addAll(data)
            }
            notifyDataSetChanged()
        }
        override fun getItemCount(): Int = list.size
        override fun onBindViewHolder(
            holder: BindingViewHolder<ItemSuqareListBinding>,
            position: Int
        ) {
            val info = list[position]
            Glide.with(holder.binding.itemImg).load(info.liveCoverUrl)
                .error(R.drawable.edit_bg)
                .transform(RoundedCorners(20))
                .into(holder.binding.itemImg)
            holder.binding.isLived.visibility = if (info.liveStatus == 1) {
                View.VISIBLE
            } else {
                View.GONE
            }
            holder.binding.title.text = info.nickName
            holder.binding.sign.text = info.liveTitle
            holder.itemView.setOnClickListener {
                function.invoke(info)
            }
        }
    }
}